<template>
  <div class="page-wrapper">
    <TopNav />
    <!-- <SubNav /> -->
    <div class="article-page">
      <!-- 添加锚点导航 -->
      <div class="anchor-nav" v-if="anchors.length > 0">
        <div class="anchor-title">Navigation</div>
        <div class="anchor-list">
          <div class="anchor-section">
            <div 
              class="anchor-section-title" 
              @click="scrollToSection('paragraph-0', 'paragraph-0', 'news-content')"
            >News Content</div>
            <div class="anchor-section-items">
              <div 
                v-for="anchor in contentAnchors" 
                :key="anchor.id"
                class="anchor-item"
                :class="{ active: currentAnchor === anchor.id }"
                @click="scrollToSection(anchor.id, anchor.id, 'news-content')"
              >
                {{ anchor.text }}
              </div>
            </div>
          </div>
          <div class="anchor-section">
            <div 
              class="anchor-section-title" 
              @click="scrollToSection('quiz-1', 'quiz-1', 'news-training')"
            >News Training</div>
            <div class="anchor-section-items">
              <div 
                class="anchor-item" 
                :class="{ active: currentAnchor === 'quiz-1' }"
                @click="scrollToSection('quiz-1', 'quiz-1', 'news-training')"
              >Reading Comprehension 1</div>
              <div 
                class="anchor-item" 
                :class="{ active: currentAnchor === 'quiz-2' }"
                @click="scrollToSection('quiz-2', 'quiz-2', 'news-training')"
              >Reading Comprehension 2</div>
              <div 
                class="anchor-item" 
                :class="{ active: currentAnchor === 'quiz-3' }"
                @click="scrollToSection('quiz-3', 'quiz-3', 'news-training')"
              >Reading Comprehension 3</div>
              <div 
                class="anchor-item" 
                :class="{ active: currentAnchor === 'quiz-4' }"
                @click="scrollToSection('quiz-4', 'quiz-4', 'news-training')"
              >Reading Comprehension 4</div>
            </div>
          </div>
        </div>
      </div>

      <div class="content-wrapper">
        <div class="article-container">
          <div class="article-header">
            <h1 class="article-title">{{ article.title }}</h1>
            <div class="article-meta">
              <span class="article-author">By {{ article.author }}</span>
              <span class="article-date">{{ article.date }}</span>
              <span class="article-readtime">{{ article.readTime }}</span>
            </div>
          </div>
          <div class="article-content" ref="content">
            <img v-if="article.image" :src="article.image" :alt="article.title" class="article-image">
            <div id="news-content" class="content-section-title section-anchor"></div>
            <div class="article-text" v-html="article.content"></div>
            <div id="news-training" class="content-section-title section-anchor"></div>
            <div class="reading-quiz">
              <div id="quiz-1" class="quiz-question">
                <h3>Reading Comprehension 1</h3>
                <p>According to the article, who will Mark Carney replace as the leader of the Liberal Party and Prime Minister of Canada?</p>
                <div class="quiz-options">
                  <div 
                    v-for="(option, index) in quizOptions1" 
                    :key="index"
                    class="quiz-option"
                    :class="{ 
                      'selected': selectedOption1 === option.value,
                      'correct': showResult1 && option.value === correctAnswer1,
                      'incorrect': showResult1 && selectedOption1 === option.value && option.value !== correctAnswer1
                    }"
                    @click="selectOption(1, option.value)"
                  >
                    <span class="option-label">{{ option.label }}</span>
                    {{ option.text }}
                  </div>
                </div>
                <div v-if="showResult1" class="quiz-result">
                  <div v-if="selectedOption1 === correctAnswer1" class="result-correct">
                    <span>✓ Correct!</span>
                  </div>
                  <div v-else class="result-incorrect">
                    <span>✗ Incorrect</span>
                    <p class="explanation">Explanation: Justin Trudeau is the current Prime Minister of Canada, and the article clearly states that Mark Carney will replace his position.</p>
                  </div>
                </div>
              </div>

              <div id="quiz-2" class="quiz-question">
                <h3>Reading Comprehension 2</h3>
                <p>According to the article, what action is Mark Carney expected to take after taking office?</p>
                <div class="quiz-options">
                  <div 
                    v-for="(option, index) in quizOptions2" 
                    :key="index"
                    class="quiz-option"
                    :class="{ 
                      'selected': selectedOption2 === option.value,
                      'correct': showResult2 && option.value === correctAnswer2,
                      'incorrect': showResult2 && selectedOption2 === option.value && option.value !== correctAnswer2
                    }"
                    @click="selectOption(2, option.value)"
                  >
                    <span class="option-label">{{ option.label }}</span>
                    {{ option.text }}
                  </div>
                </div>
                <div v-if="showResult2" class="quiz-result">
                  <div v-if="selectedOption2 === correctAnswer2" class="result-correct">
                    <span>✓ Correct!</span>
                  </div>
                  <div v-else class="result-incorrect">
                    <span>✗ Incorrect</span>
                    <p class="explanation">Explanation: The article mentions "He's expected to quickly call a federal election", indicating that he is expected to quickly call a federal election.</p>
                  </div>
                </div>
              </div>

              <div id="quiz-3" class="quiz-question">
                <h3>Reading Comprehension 3</h3>
                <p>According to the article, what is the background of this leadership change?</p>
                <div class="quiz-options">
                  <div 
                    v-for="(option, index) in quizOptions3" 
                    :key="index"
                    class="quiz-option"
                    :class="{ 
                      'selected': selectedOption3 === option.value,
                      'correct': showResult3 && option.value === correctAnswer3,
                      'incorrect': showResult3 && selectedOption3 === option.value && option.value !== correctAnswer3
                    }"
                    @click="selectOption(3, option.value)"
                  >
                    <span class="option-label">{{ option.label }}</span>
                    {{ option.text }}
                  </div>
                </div>
                <div v-if="showResult3" class="quiz-result">
                  <div v-if="selectedOption3 === correctAnswer3" class="result-correct">
                    <span>✓ Correct!</span>
                  </div>
                  <div v-else class="result-incorrect">
                    <span>✗ Incorrect</span>
                    <p class="explanation">Explanation: The article mentions "amid threats from the U.S.", indicating that this change occurs against the backdrop of threats from the United States.</p>
                  </div>
                </div>
              </div>

              <div id="quiz-4" class="quiz-question">
                <h3>Reading Comprehension 4</h3>
                <p>What position did Mark Carney previously hold?</p>
                <div class="quiz-options">
                  <div 
                    v-for="(option, index) in quizOptions4" 
                    :key="index"
                    class="quiz-option"
                    :class="{ 
                      'selected': selectedOption4 === option.value,
                      'correct': showResult4 && option.value === correctAnswer4,
                      'incorrect': showResult4 && selectedOption4 === option.value && option.value !== correctAnswer4
                    }"
                    @click="selectOption(4, option.value)"
                  >
                    <span class="option-label">{{ option.label }}</span>
                    {{ option.text }}
                  </div>
                </div>
                <div v-if="showResult4" class="quiz-result">
                  <div v-if="selectedOption4 === correctAnswer4" class="result-correct">
                    <span>✓ Correct!</span>
                  </div>
                  <div v-else class="result-incorrect">
                    <span>✗ Incorrect</span>
                    <p class="explanation">Explanation: From the article title "Former Bank of Canada Chief", we can see that he previously served as the Governor of the Bank of Canada.</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 添加右侧工具栏 -->
      <div class="right-sidebar">
        <t-space direction="vertical" size="large">
          <t-sticky-tool
            :style="{ position: 'fixed', right: '80px', top: '45%', height:'130px', transform: 'translateY(-50%)', backgroundColor: '#fff', borderRadius: '8px', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"
            @click="handleStickyClick"
            @hover="handleStickyHover"
          >
            <t-sticky-item label="Vocabulary" @click="toggleVocabularyPanel">
              <template #icon>
                <BookUnknownIcon />
              </template>
            </t-sticky-item>
            <t-sticky-item label="Translation" @click="toggleGrammarPanel">
              <template #icon>
                <BookIcon />
              </template>
            </t-sticky-item>
          </t-sticky-tool>

          <t-sticky-tool
            :style="{ position: 'fixed', right: '80px', top: '70%', height:'65px', transform: 'translateY(-50%)', backgroundColor: '#fff', borderRadius: '8px', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"
            @click="handleStickyClick"
            @hover="handleStickyHover"
          >
            <t-sticky-item label="Discussion">
              <template #icon>
                <ChatBubbleIcon />
              </template>
            </t-sticky-item>
          </t-sticky-tool>
        </t-space>
      </div>
    </div>

    <!-- 添加词汇本面板 -->
    <div class="side-panel" :class="{ 'show': showVocabularyPanel }">
      <div class="panel-header">
        <h3>Vocabulary</h3>
        <button class="close-btn" @click="toggleVocabularyPanel">×</button>
      </div>
      <div class="panel-content">
        <div v-for="(word, index) in vocabularyList" :key="index" class="vocabulary-item">
          <div class="item-content">
            <div class="word">{{ word.english }}</div>
            <div class="translation">{{ word.chinese }}</div>
          </div>
          <button class="delete-btn" @click="deleteVocabulary(index)">×</button>
        </div>
      </div>
    </div>

    <!-- 添加翻译本面板 -->
    <div class="side-panel" :class="{ 'show': showGrammarPanel }">
      <div class="panel-header">
        <h3>Translation</h3>
        <button class="close-btn" @click="toggleGrammarPanel">×</button>
      </div>
      <div class="panel-content">
        <div v-for="(item, index) in grammarList" :key="index" class="grammar-item">
          <div class="item-content">
            <div class="pattern">{{ item.pattern }}</div>
            <div class="explanation">{{ item.explanation }}</div>
          </div>
          <button class="delete-btn" @click="deleteGrammar(index)">×</button>
        </div>
      </div>
    </div>

    <!-- 添加讨论面板 -->
    <div class="side-panel" :class="{ 'show': showDiscussionPanel }">
      <div class="panel-header">
        <h3>Discussion</h3>
        <button class="close-btn" @click="toggleDiscussionPanel">×</button>
      </div>
      <div class="panel-content discussion-panel">
        <div class="chat-container">
          <div class="chat-messages" ref="chatMessages">
            <div v-for="(item, index) in chatList" :key="index" 
              :class="['message', item.role === 'user' ? 'message-right' : 'message-left']">
              <div class="message-avatar">
                <img :src="item.avatar" :alt="item.name">
              </div>
              <div class="message-content">
                <div class="message-info">
                  <span class="message-name">{{ item.name }}</span>
                  <span class="message-time">{{ item.datetime }}</span>
                </div>
                <div class="message-text" v-html="item.content"></div>
                <div v-if="item.loading" class="message-loading">
                  <!-- <div class="chat-loading chat-loading-moving"></div>
                  <div class="chat-loading chat-loading-gradient"></div> -->
                  <!-- <t-chat-loading animation="gradient" /> -->
                </div>
                <div class="message-actions" v-if="item.role === 'assistant' && !item.loading">
                  <!-- <button 
                    class="action-btn" 
                    :class="{ active: isGood }"
                    @click="handleOperation('good', { index })">
                    👍
                  </button>
                  <button 
                    class="action-btn"
                    :class="{ active: isBad }"
                    @click="handleOperation('bad', { index })">
                    👎
                  </button> -->
                </div>
              </div>
            </div>
          </div>
          <div class="chat-input">
            <div class="input-container">
              <textarea 
                v-model="inputMessage" 
                @keyup.enter="handleEnter"
                placeholder="Enter message..."
                rows="1"
              ></textarea>
              <button class="send-btn" @click="handleSend" :disabled="isStreamLoad">
                发送
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加翻译按钮和面板 -->
    <div 
      class="translate-button" 
      :style="{ 
        left: translateButtonPosition.x + 'px',
        top: translateButtonPosition.y + 'px',
        display: showTranslateButton ? 'block' : 'none'
      }"
    >
      <div class="translate-icon" @click.prevent="handleTranslate">
        <t-icon name="translate" />
      </div>
      <div class="close-translate-button" @click="showTranslateButton = false">×</div>
    </div>

    <!-- 翻译内容面板 -->
    <div 
      class="translate-panel"
      :style="{ 
        left: (translateButtonPosition.x + 40) + 'px',
        top: translateButtonPosition.y + 'px',
        display: showTranslatePanel ? 'block' : 'none'
      }"
    >
      <div class="panel-arrow"></div>
      <div class="translate-content">
        <div v-if="isTranslating" class="loading-spinner"></div>
        <div v-else>{{ translatedText }}</div>
      </div>
    </div>

    <!-- 添加单词详情面板 -->
    <div class="word-detail-panel" :class="{ 'show': showWordDetailPanel }" v-if="currentWord">
      <div class="panel-header">
        <h3>{{ currentWord.english }}</h3>
        <button class="close-btn" @click="closeWordDetail">×</button>
      </div>
      <div class="panel-content">
        <div class="word-section">
          <div class="section-title">Definition</div>
          <div class="section-content">{{ currentWord.chinese }}</div>
        </div>
        <div class="word-section">
          <div class="section-title">Phonetic</div>
          <div class="section-content">{{ currentWord.phonetic || '/' }}</div>
        </div>
        <div class="word-section">
          <div class="section-title">Part of Speech</div>
          <div class="section-content">{{ currentWord.partOfSpeech || 'n.' }}</div>
        </div>
        <div class="word-section">
          <div class="section-title">Example Sentences</div>
          <div class="section-content example-sentences">
            <div v-for="(sentence, index) in currentWord.examples" :key="index" class="example-item">
              <div class="english">{{ sentence.english }}</div>
              <div class="chinese">{{ sentence.chinese }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TopNav from './TopNav.vue'
import SubNav from './SubNav.vue'
import { BookUnknownIcon, BookIcon, ChatBubbleIcon, Icon } from 'tdesign-icons-vue-next'
import { Dialog, Space, StickyTool, StickyItem } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import { h, ref } from 'vue'
import axios from 'axios'

class MockSSEResponse {
  constructor(data) {
    this.data = data;
    this.controller = new AbortController();
  }

  async getResponse() {
    return {
      ok: true,
      body: {
        getReader: () => ({
          read: async () => {
            if (this.controller.signal.aborted) {
              return { done: true };
            }
            const chunk = this.data;
            this.data = '';
            return {
              value: new TextEncoder().encode(chunk),
              done: !chunk,
            };
          },
        }),
      },
    };
  }

  close() {
    this.controller.abort();
  }
}

export default {
  name: 'ArticlePage',
  components: {
    TopNav,
    SubNav,
    BookUnknownIcon,
    BookIcon,
    ChatBubbleIcon,
    TDialog: Dialog,
    TSpace: Space,
    TStickyTool: StickyTool,
    TStickyItem: StickyItem,
    TIcon: Icon,
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      article: {
        title: '',
        author: '',
        date: '',
        readTime: '',
        image: '',
        content: ''
      },
      anchors: [],
      contentAnchors: [],
      currentAnchor: '',
      currentSection: 'news-content',
      quizOptions1: [
        { label: 'A', text: 'Stephen Harper', value: 'harper' },
        { label: 'B', text: 'Justin Trudeau', value: 'trudeau' },
        { label: 'C', text: 'Jean Chrétien', value: 'chretien' },
        { label: 'D', text: 'Paul Martin', value: 'martin' }
      ],
      quizOptions2: [
        { label: 'A', text: 'Resign immediately', value: 'resign' },
        { label: 'B', text: 'Quickly call a federal election', value: 'election' },
        { label: 'C', text: 'Form a new government', value: 'government' },
        { label: 'D', text: 'Visit the United States', value: 'visit' }
      ],
      quizOptions3: [
        { label: 'A', text: 'Economic crisis', value: 'economy' },
        { label: 'B', text: 'Threats from the United States', value: 'threats' },
        { label: 'C', text: 'Internal divisions', value: 'internal' },
        { label: 'D', text: 'Public support', value: 'support' }
      ],
      quizOptions4: [
        { label: 'A', text: 'Governor of the Bank of Canada', value: 'bank' },
        { label: 'B', text: 'Minister of Finance', value: 'finance' },
        { label: 'C', text: 'Minister of Foreign Affairs', value: 'foreign' },
        { label: 'D', text: 'Deputy Prime Minister', value: 'deputy' }
      ],
      selectedOption1: null,
      selectedOption2: null,
      selectedOption3: null,
      selectedOption4: null,
      correctAnswer1: 'trudeau',
      correctAnswer2: 'election',
      correctAnswer3: 'threats',
      correctAnswer4: 'bank',
      showResult1: false,
      showResult2: false,
      showResult3: false,
      showResult4: false,
      showVocabularyPanel: false,
      showGrammarPanel: false,
      showDiscussionPanel: false,
      vocabularyList: [
        { english: 'former', chinese: '前任的，以前的' },
        { english: 'chief', chinese: '首领，主要的' },
        { english: 'liberal', chinese: '自由主义的，开明的' },
        { english: 'party', chinese: '政党，党派' },
        { english: 'victory', chinese: '胜利，成功' },
        { english: 'significant', chinese: '重要的，显著的' },
        { english: 'shift', chinese: '转变，改变' },
        { english: 'expertise', chinese: '专门知识，专长' },
        { english: 'crucial', chinese: '关键的，决定性的' },
        { english: 'threat', chinese: '威胁，恐吓' }
      ],
     grammarList: [
        { 
          pattern: 'Former Bank of Canada Chief',
          explanation: '加拿大银行前行长' 
        },
        { 
          pattern: 'amid threats from the U.S.',
          explanation: '在来自美国的威胁之中' 
        },
        { 
          pattern: 'is expected to quickly call a federal election',
          explanation: '预计将很快召开联邦选举' 
        },
        { 
          pattern: 'marks a significant shift',
          explanation: '标志着重大转变' 
        }
      ],
      showTranslateButton: false,
      showTranslatePanel: false,
      translateButtonPosition: {
        x: 0,
        y: 0
      },
      selectedText: '',
      isTranslating: false,
      translatedText: '',
      fetchCancel: null,
      loading: false,
      isStreamLoad: false,
      isGood: false,
      isBad: false,
      chatRef: null,
      chatList: [],
      inputMessage: '',
      showWordDetailPanel: false,
      currentWord: null,
      wordDetails: {
        'former': {
          english: 'former',
          chinese: '以前的，从前的',
          phonetic: '/ˈfɔːrmər/',
          partOfSpeech: 'adj.',
          examples: [
            {
              english: 'He is the former president of the company.',
              chinese: '他是公司的前任总裁。'
            },
            {
              english: 'She returned to her former job.',
              chinese: '她回到了她以前的工作。'
            }
          ]
        },
        'chief': {
          english: 'chief',
          chinese: '首领，主要的',
          phonetic: '/tʃiːf/',
          partOfSpeech: 'n. & adj.',
          examples: [
            {
              english: 'He was appointed as the new police chief.',
              chinese: '他被任命为新的警察局长。'
            },
            {
              english: 'The chief reason for her success is hard work.',
              chinese: '她成功的主要原因是努力工作。'
            }
          ]
        },
        // 可以继续添加更多单词的详细信息
      }
    }
  },
  created() {
    // 使用props中的id或路由参数
    const articleId = this.id || this.$route.params.id;
    this.fetchArticle(articleId);
  },
  mounted() {
    this.$nextTick(() => {
      this.generateAnchors();
      window.addEventListener('scroll', this.handleScroll);
      document.addEventListener('mouseup', this.handleMouseUp);
      document.addEventListener('mousedown', this.handleMouseDown);
      // 添加点击事件监听
      document.addEventListener('click', this.handleWordClick);
    });
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
    document.removeEventListener('mouseup', this.handleMouseUp);
    document.removeEventListener('mousedown', this.handleMouseDown);
    // 移除点击事件监听
    document.removeEventListener('click', this.handleWordClick);
  },
  methods: {
    fetchArticle(id) {
      // 根据不同的文章ID返回不同的内容
      const articles = {
        'main-1': {
          title: 'Former Bank of Canada Chief Wins Race to Lead Liberal Party, and Canada',
          author: 'John Smith',
          date: '2024年3月9日',
          readTime: '4 分钟阅读',
          image: 'https://s1.mintiny.com/wlake/i/2025/03/11/1fkkdl.png',
          content: `
            <p>Mark Carney will replace Justin Trudeau as party leader and the country's prime minister amid threats from the U.S.In a dramatic shift in Canadian politics, former Bank of Canada Governor and United Nations climate envoy Mark Carney is poised to replace Justin Trudeau as leader of the Liberal Party and Prime Minister of Canada. The sudden announcement comes amid escalating tensions with the United States, where economic and environmental disputes have fueled concerns over cross-border stability. Carney, known for his pragmatic approach to global challenges and his experience in navigating high-stakes diplomatic and financial negotiations, is seen by many as a stabilizing force in a time of uncertainty.</p>
           
            <p>Trudeau’s decision to step down follows a series of setbacks, including strained relations with the U.S. over trade policies and energy infrastructure projects. The Biden administration’s aggressive stance on climate action and its push for domestic manufacturing subsidies have put Canadian industries, particularly in the energy sector, under significant pressure. Meanwhile, domestic critics argue that Trudeau’s government failed to adequately address inflation, housing affordability, and supply chain disruptions, eroding public confidence.</p>


             
            <p>Carney’s appointment signals a strategic pivot for the Liberal Party. With a background in economics and climate policy, he is expected to prioritize diplomatic reconciliation with the U.S. while advocating for Canadian interests. His tenure at the Bank of Canada, where he championed financial stability and sustainable growth, and his later role as the UN’s Special Envoy for Climate Action, position him uniquely to address both economic and environmental challenges.</p>

             
            <p>“Canada cannot afford to be sidelined in a rapidly changing global landscape,” said a senior Liberal Party official. “Carney’s international experience and track record of fostering cooperation will be critical in rebuilding trust with our closest ally while safeguarding Canadian sovereignty.”</p>

             
            <p>Carney’s platform is expected to focus on three pillars: strengthening economic resilience through innovation and green investments, renegotiating trade agreements to protect Canadian industries, and fostering unity in a politically divided nation. His emphasis on climate policy could also align Canada more closely with European partners, potentially reducing reliance on U.S. markets.</p>

             
            <p>However, challenges loom large. Conservative opponents have already criticized Carney as an “outsider” with no elected mandate, while progressive factions within the Liberal Party worry that his corporate-friendly reputation may dilute commitments to social programs. Additionally, mending ties with the U.S. will require delicate diplomacy, as American lawmakers remain skeptical of Canadian positions on pipelines and fossil fuel exports.</p>

             
            <p>As Carney prepares to take the helm, the world watches closely. His ability to balance domestic priorities with international pressures will not only determine Canada’s future but could also set a precedent for how democracies navigate geopolitical turbulence in the 21st century. For now, the question remains: Can Mark Carney transform a moment of crisis into an opportunity for renewal?</p>

          `
        },
        'secondary-1': {
          title: 'Will Canadians Warm Up to Mark Carney?',
          author: 'Sarah Johnson',
          date: '2024年3月9日',
          readTime: '5 分钟阅读',
          image: 'https://s1.mintiny.com/wlake/i/2025/03/10/mzl5.png',
          content: `
            <p>Despite his impressive credentials, some voters remain skeptical of the former banker's ability to connect with ordinary Canadians.</p>
            <p>此处可以添加更多详细内容...</p>
          `
        },
        'food-1': {
          title: 'All-Purpose Biscuits That Anyone Can Make (Really!)',
          author: 'Christopher Testani',
          date: '2024年3月9日',
          readTime: '6 分钟阅读',
          image: 'https://hebbkx1anhila5yf.public.blob.vercel-storage.com/image-bzTRQM3Dsw3QBuWavTHLQLzD9Z9VVH.png',
          content: `
            <p>"I'm 78, Southern and these were the best biscuits I've ever made," wrote one reader.</p>
            <p>Our step-by-step guide breaks down the secret to achieving the perfect flaky layers every time.</p>
            <div class="recipe-details">
              <p><strong>准备时间：</strong> 20分钟</p>
              <p><strong>难度：</strong> 简单</p>
            </div>
            <p>此处可以添加详细的制作步骤...</p>
          `
        }
      };

      // 获取对应ID的文章内容
      const article = articles[id] || {
        title: '文章未找到',
        author: 'Unknown',
        date: new Date().toLocaleDateString(),
        readTime: '0 分钟阅读',
        image: '',
        content: '<p>抱歉，该文章不存在或已被删除。</p>'
      };

      // 处理文章内容,将单词转换为可点击的形式
      article.content = this.convertWordsToClickable(article.content);
      this.article = article;
    },

    convertWordsToClickable(content) {
      // 使用DOMParser解析HTML内容
      const parser = new DOMParser();
      const doc = parser.parseFromString(content, 'text/html');
      
      // 处理所有段落
      doc.querySelectorAll('p').forEach(p => {
        // 获取段落文本
        const text = p.textContent;
        // 将文本分割成单词，保留标点符号
        const words = text.match(/\b\w+\b|\W+/g) || [];
        // 将每个单词转换为可点击的span
        const newContent = words.map(word => {
          // 如果是单词（不是标点符号或空格）
          if (/^\w+$/.test(word)) {
            return `<span class="clickable-word" role="button" tabindex="0">${word}</span>`;
          }
          return word;
        }).join('');
        // 更新段落内容
        p.innerHTML = newContent;
      });
      
      return doc.body.innerHTML;
    },

    generateAnchors() {
      const content = this.$refs.content;
      if (!content) return;

      // 获取新闻正文部分的段落
      const articleText = content.querySelector('.article-text');
      if (!articleText) return;

      const paragraphs = articleText.querySelectorAll('p');
      
      this.contentAnchors = Array.from(paragraphs).map((el, index) => {
        const id = `paragraph-${index}`;
        el.id = id;
        return {
          id,
          text: el.textContent.slice(0, 15) + '...',
          element: el
        };
      });

      // 添加阅读理解部分的锚点
      const quizAnchors = ['quiz-1', 'quiz-2', 'quiz-3', 'quiz-4'].map(id => ({
        id,
        text: `Reading Comprehension ${id.split('-')[1]}`,
        element: document.getElementById(id)
      }));

      // 合并所有锚点
      this.anchors = [...this.contentAnchors, ...quizAnchors];
    },
    scrollToSection(id, anchorId, section) {
      const element = document.getElementById(id);
      if (element) {
        const elementRect = element.getBoundingClientRect();
        const absoluteElementTop = elementRect.top + window.pageYOffset;
        const middleScrollPosition = absoluteElementTop - (window.innerHeight / 2) + (elementRect.height / 2);
        
        // 检查是否超出底部
        const documentHeight = Math.max(
          document.body.scrollHeight,
          document.body.offsetHeight,
          document.documentElement.clientHeight,
          document.documentElement.scrollHeight,
          document.documentElement.offsetHeight
        );
        const maxScroll = documentHeight - window.innerHeight;
        const finalScrollPosition = Math.min(middleScrollPosition, maxScroll);
        
        window.scrollTo({
          top: Math.max(0, finalScrollPosition),
          behavior: 'smooth'
        });

        if (anchorId) {
          this.currentAnchor = anchorId;
        }
        if (section) {
          this.currentSection = section;
        }
      }
    },
    scrollToAnchor(id) {
      const element = document.getElementById(id);
      if (element) {
        const elementRect = element.getBoundingClientRect();
        const absoluteElementTop = elementRect.top + window.pageYOffset;
        const middleScrollPosition = absoluteElementTop - (window.innerHeight / 2) + (elementRect.height / 2);
        
        // 检查是否超出底部
        const documentHeight = Math.max(
          document.body.scrollHeight,
          document.body.offsetHeight,
          document.documentElement.clientHeight,
          document.documentElement.scrollHeight,
          document.documentElement.offsetHeight
        );
        const maxScroll = documentHeight - window.innerHeight;
        const finalScrollPosition = Math.min(middleScrollPosition, maxScroll);
        
        window.scrollTo({
          top: Math.max(0, finalScrollPosition),
          behavior: 'smooth'
        });

        this.currentAnchor = id;
      }
    },
    handleScroll() {
      const scrollPosition = window.scrollY;
      const windowHeight = window.innerHeight;
      
      // 找到当前视窗中最接近顶部的元素
      let closestElement = null;
      let closestDistance = Infinity;
      
      this.anchors.forEach(anchor => {
        const element = document.getElementById(anchor.id);
        if (element) {
          const rect = element.getBoundingClientRect();
          // 计算元素中心点到视窗中心的距离
          const distance = Math.abs(rect.top + rect.height / 2 - windowHeight / 2);
          
          if (distance < closestDistance) {
            closestDistance = distance;
            closestElement = anchor;
          }
        }
      });
      
      if (closestElement) {
        // 如果是阅读理解部分的锚点
        if (closestElement.id.startsWith('quiz-')) {
          this.currentAnchor = closestElement.id;
          this.currentSection = 'news-training';
        } else {
          // 如果是新闻正文部分的锚点
          this.currentAnchor = closestElement.id;
          this.currentSection = 'news-content';
        }
      }
    },
    renderQrIcon() {
      return h(QrcodeIcon);
    },
    renderPopup() {
      return h('img', {
        alt: 'QR Code',
        width: 120,
        height: 120,
        src: 'https://tdesign.gtimg.com/site/site.jpg'
      });
    },
    handleStickyClick(context) {
      if (context.item.label === 'Vocabulary') {
        this.toggleVocabularyPanel();
      } else if (context.item.label === 'Translation') {
        this.toggleGrammarPanel();
      } else if (context.item.label === 'Discussion') {
        this.toggleDiscussionPanel();
      }
    },
    handleStickyHover(context) {
      console.log('hover', context);
    },
    selectOption(quizNumber, value) {
      const optionKey = `selectedOption${quizNumber}`;
      const resultKey = `showResult${quizNumber}`;
      
      if (this[resultKey]) return;
      this[optionKey] = value;
      this[resultKey] = true;
    },
    goToDiscussion() {
      this.toggleDiscussionPanel();
    },
    toggleVocabularyPanel() {
      console.log('Toggling vocabulary panel');
      this.showVocabularyPanel = !this.showVocabularyPanel;
      // 关闭另一个面板
      if (this.showVocabularyPanel) {
        this.showGrammarPanel = false;
        this.showDiscussionPanel = false;
      }
    },
    toggleGrammarPanel() {
      console.log('Toggling grammar panel');
      this.showGrammarPanel = !this.showGrammarPanel;
      // 关闭另一个面板
      if (this.showGrammarPanel) {
        this.showVocabularyPanel = false;
        this.showDiscussionPanel = false;
      }
    },
    toggleDiscussionPanel() {
      console.log('Toggling discussion panel');
      this.showDiscussionPanel = !this.showDiscussionPanel;
      // 关闭另一个面板
      if (this.showDiscussionPanel) {
        this.showVocabularyPanel = false;
        this.showGrammarPanel = false;
        
        // 当打开讨论面板时，自动开始流式输出
        // 首先清空现有的聊天列表并添加一个新的AI消息
        this.chatList = [];
        
        // 添加AI消息
        const aiParams = {
          avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
          name: 'TDesignAI',
          datetime: new Date().toLocaleString(),
          content: 'You can ask me anything about the news.',
          role: 'assistant',
          loading: true
        };
        this.chatList.push(aiParams);
        
        // 开始流式输出
        this.$nextTick(() => {
          this.autoStreamOutput();
        });
      }
    },
    handleMouseUp(event) {
      const selection = window.getSelection();
      const selectedText = selection.toString().trim();
      
      if (selectedText && this.isArticleContent(event.target)) {
        this.selectedText = selectedText;
        
        // 使用鼠标事件的坐标来定位按钮
        this.translateButtonPosition = {
          x: event.pageX,
          y: event.pageY
        };
        
        this.showTranslateButton = true;
      }
    },
    
    handleMouseDown(event) {
      // 如果点击的是翻译按钮或翻译面板，不做任何处理
      if (event.target.closest('.translate-button') || 
          event.target.closest('.translate-panel')) {
        event.preventDefault();
        event.stopPropagation();
        return;
      }
      
      // 点击其他区域时，隐藏翻译按钮和面板
      this.showTranslateButton = false;
      this.showTranslatePanel = false;
    },
    
    isArticleContent(element) {
      // 检查选中的文本是否在文章内容区域内
      return element.closest('.article-content') !== null;
    },
    async handleTranslate(event) {
      // 阻止默认行为，保持文本选中状态
      event.preventDefault();
      event.stopPropagation();
      
      // 保存当前选择
      const selection = window.getSelection();
      const range = selection.getRangeAt(0);
      
      // 获取选中的文本
      const selectedText = this.selectedText.trim();
      
      if (selectedText) {
        // 将选中的文本添加到grammarList中
        this.grammarList.push({
          pattern: selectedText,
          explanation: '在美国的威胁下，马克·卡尼将取代贾斯汀·特鲁多成为加拿大党领袖和总理'
        });
        
        // 显示成功消息
        MessagePlugin.success({
          content: `Text "${selectedText}" has been added to translation book`,
          duration: 2000
        });
      }
      
      // 显示翻译面板并开始加载
      this.showTranslatePanel = true;
      this.isTranslating = true;
      this.translatedText = '';
      
      try {
        // 等待2秒
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        // 显示固定的翻译文本，不发起真正的翻译请求
        this.translatedText = "在美国的威胁下，马克·卡尼将取代贾斯汀·特鲁多成为加拿大党领袖和总理";
        
        // 模拟记录日志
        console.log('Selected text:', this.selectedText);
        console.log('Fixed translation displayed');
      } catch (error) {
        console.error('翻译过程出错:', error);
        this.translatedText = '翻译失败，请重试';
      } finally {
        this.isTranslating = false;
      }
    },
    clearConfirm() {
      this.chatList = [];
    },
    onStop() {
      if (this.fetchCancel) {
        this.fetchCancel.controller.close();
        this.loading = false;
      }
    },
    handleOperation(type, options) {
      console.log('handleOperation', type, options);
      const { index } = options;
      if (type === 'good') {
        this.isGood = !this.isGood;
        this.isBad = false;
      } else if (type === 'bad') {
        this.isBad = !this.isBad;
        this.isGood = false;
      } else if (type === 'replay') {
        const userQuery = this.chatList[index + 1].content;
        this.inputEnter(userQuery);
      }
    },
    handleEnter(e) {
      if (e.shiftKey) return;
      e.preventDefault();
      this.handleSend();
    },
    handleSend() {
      if (!this.inputMessage.trim() || this.isStreamLoad) return;
      this.inputEnter(this.inputMessage);
      this.inputMessage = '';
    },
    async inputEnter(inputValue) {
      if (this.isStreamLoad) return;
      if (!inputValue) return;
      
      // 添加用户消息
      const userParams = {
        avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
        name: 'Me',
        datetime: new Date().toLocaleString(),
        content: inputValue,
        role: 'user',
        loading: false
      };
      this.chatList.push(userParams);
      
      // 滚动到底部
      this.$nextTick(() => {
        const chatMessages = this.$refs.chatMessages;
        if (chatMessages) {
          chatMessages.scrollTop = chatMessages.scrollHeight;
        }
      });
      
      // 如果是特定问题，显示预设的对话
      if (inputValue.includes("how might Mark Carney's background")) {
        const dialogues = [
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Teacher',
            content: "Mark Carney's economic expertise suggests he might focus more on financial stability and international trade. As a former central banker, he likely has experience managing economic crises and negotiating with global partners. This could be crucial given the threats from the U.S. and Canada's current economic challenges. Justin Trudeau's policies were more focused on social issues and environmental goals, so there might be a significant shift in priorities.",
            role: 'assistant'
          },
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Struggling Student',
            content: 'Thank you, teacher! So, does "central banker" mean someone who works with money and banks?',
            role: 'assistant'
          },
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Advanced Student',
            content: 'Exactly! A central banker manages a country\'s money supply, sets interest rates, and ensures the financial system works smoothly. Mark Carney was the Governor of the Bank of Canada before, so he has a strong background in economics.',
            role: 'assistant'
          },
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Culture Interpreter',
            content: "It's also worth noting that Mark Carney has international experience, including leading the Bank of England. This global perspective might help Canada navigate tensions with the U.S. and strengthen its position in international affairs.",
            role: 'assistant'
          }
        ];
        
        // 逐条显示对话
        for (const dialogue of dialogues) {
          await new Promise(resolve => setTimeout(resolve, 3000));
          
          const newMessage = {
            ...dialogue,
            datetime: new Date().toLocaleString(),
            loading: false
          };
          this.chatList.push(newMessage);
          
          // 滚动到底部
          this.$nextTick(() => {
            const chatMessages = this.$refs.chatMessages;
            if (chatMessages) {
              chatMessages.scrollTop = chatMessages.scrollHeight;
            }
          });
        }
      }
       // 如果是特定问题，显示预设的对话
       if (inputValue.includes("Do you think Mark Carney's leadership")) {
        const dialogues = [
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Teacher',
            content: "Given the urgency of the situation and the threats from the U.S., Mark Carney might adopt a more authoritative approach to quickly implement economic reforms. However, his background also suggests he values expertise and data-driven decisions, so he might collaborate with economists and international partners to address challenges effectively.",
            role: 'assistant'
          },
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Struggling Student',
            content: 'I see! So, calling a federal election quickly means he wants people to support his plans right away.',
            role: 'assistant'
          },
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Advanced Student',
            content: 'Yes! By holding an election soon, he can gain a mandate from voters to push his policies forward. It shows confidence in his ability to handle the current crises.',
            role: 'assistant'
          },
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Culture Interpreter',
            content: "It's also worth noting that Mark Carney has international experience, including leading the Bank of England. This global perspective might help Canada navigate tensions with the U.S. and strengthen its position in international affairs.",
            role: 'assistant'
          }
        ];
        
        // 逐条显示对话
        for (const dialogue of dialogues) {
          await new Promise(resolve => setTimeout(resolve, 3000));
          
          const newMessage = {
            ...dialogue,
            datetime: new Date().toLocaleString(),
            loading: false
          };
          this.chatList.push(newMessage);
          
          // 滚动到底部
          this.$nextTick(() => {
            const chatMessages = this.$refs.chatMessages;
            if (chatMessages) {
              chatMessages.scrollTop = chatMessages.scrollHeight;
            }
          });
        }
      }
      if (inputValue.includes("Thank you all for explaining!")) {
        const dialogues = [
          {
            avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
            name: 'Teacher',
            content: "You're welcome! Remember, asking questions is the best way to learn. Let's continue to explore how these political changes might impact Canada's future.",
            role: 'assistant'
          },
        ];
        
        // 逐条显示对话
        for (const dialogue of dialogues) {
          await new Promise(resolve => setTimeout(resolve, 3000));
          
          const newMessage = {
            ...dialogue,
            datetime: new Date().toLocaleString(),
            loading: false
          };
          this.chatList.push(newMessage);
          
          // 滚动到底部
          this.$nextTick(() => {
            const chatMessages = this.$refs.chatMessages;
            if (chatMessages) {
              chatMessages.scrollTop = chatMessages.scrollHeight;
            }
          });
        }
      }
    },
    async handleData(inputValue) {
      this.loading = true;
      this.isStreamLoad = true;
      const lastItem = this.chatList[this.chatList.length - 1];
      lastItem.loading = true;
      
      
      // 使用Promise和setTimeout来模拟字符一个接一个地输出
      for (let i = 0; i < chars.length; i++) {
        await new Promise(resolve => setTimeout(resolve, 100));
        lastItem.content += chars[i];
      }
      
      // 输出完成后
      lastItem.loading = false;
      this.isStreamLoad = false;
      this.loading = false;
      
      // 滚动到底部
      this.$nextTick(() => {
        const chatMessages = this.$refs.chatMessages;
        if (chatMessages) {
          chatMessages.scrollTop = chatMessages.scrollHeight;
        }
      });
    },
    // 新增自动流式输出方法
    async autoStreamOutput() {
      const lastItem = this.chatList[this.chatList.length - 1];
      lastItem.loading = true;
      
      // 定义对话内容
      const dialogues = [
        {
          avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
          name: 'Struggling Student',
          content: 'Excuse me, teacher. What does "federal election" mean? I don\'t understand this word.',
          role: 'assistant'
        },
        {
          avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
          name: 'Advanced Student',
          content: 'A federal election is when people in a country vote to choose their leaders for the national government. In Canada, it\'s when they select members of parliament and the prime minister. Mark Carney is expected to call one soon because he wants to become prime minister quickly.',
          role: 'assistant'
        },
        {
          avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
          name: 'Teacher',
          content: 'Great explanation, Advanced Student! To add, a federal election in Canada is held every four years, but the prime minister can call one earlier if needed. Since Mark Carney is taking over as party leader amid U.S. threats, he might want to seek public support quickly to stabilize the situation.',
          role: 'assistant'
        },
        {
          avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
          name: 'Culture Interpreter',
          content: 'This news also reflects the close relationship between Canada and the U.S. The "threats from the U.S." might relate to trade agreements like NAFTA (North American Free Trade Agreement). Canada often faces pressure from the U.S. due to their economic interdependence. Understanding this context helps explain why leadership changes in Canada can be influenced by external factors.',
          role: 'assistant'
        }
      ];
      
      // 逐条显示对话
      for (const dialogue of dialogues) {
        // 添加新消息
        const newMessage = {
          ...dialogue,
          datetime: new Date().toLocaleString(),
          loading: false
        };
        this.chatList.push(newMessage);
        
        // 滚动到底部
        this.$nextTick(() => {
          const chatMessages = this.$refs.chatMessages;
          if (chatMessages) {
            chatMessages.scrollTop = chatMessages.scrollHeight;
          }
        });
        
        // 等待一段时间再显示下一条
        await new Promise(resolve => setTimeout(resolve, 3000));
      }
      
      // 完成
      lastItem.loading = false;
    },
    handleWordClick(event) {
      // 检查是否点击了带有clickable-word类的元素
      if (!event.target.classList.contains('clickable-word')) return;
      
      // 获取点击的文本
      const clickedText = event.target.textContent.trim().toLowerCase();
      
      // 检查是否已经存在于词汇本中
      const exists = this.vocabularyList.some(item => item.english.toLowerCase() === clickedText);
      
      if (!exists) {
        // 添加到词汇本
        this.vocabularyList.push({
          english: clickedText,
          chinese: '点击添加翻译'
        });
        
        // 显示提示消息
        MessagePlugin.success({
          content: `Word "${clickedText}" has been added to vocabulary`,
          duration: 2000
        });
      }
      
      // 显示单词详情
      if (this.wordDetails[clickedText]) {
        this.currentWord = this.wordDetails[clickedText];
        this.showWordDetailPanel = true;
        // 关闭其他面板
        this.showVocabularyPanel = false;
        this.showGrammarPanel = false;
        this.showDiscussionPanel = false;
      }
    },
    deleteVocabulary(index) {
      this.vocabularyList.splice(index, 1);
      MessagePlugin.success({
        content: 'Deleted successfully',
        duration: 2000
      });
    },
    deleteGrammar(index) {
      this.grammarList.splice(index, 1);
      MessagePlugin.success({
        content: 'Deleted successfully',
        duration: 2000
      });
    },
    closeWordDetail() {
      this.showWordDetailPanel = false;
      this.currentWord = null;
    }
  }
}
</script>

<style scoped>
.page-wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #fff;
}

.article-page {
  position: relative;
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 0;
}

.content-wrapper {
  width: 100%;
  max-width: 800px;
  padding: 20px 0;
}

.article-container {
  background: transparent;
  border-radius: 0;
  box-shadow: none;
  overflow: hidden;
}

.article-header {
  padding: 30px;
  border-bottom: 1px solid #e2e2e2;
  text-align: left; /* 确保标题左对齐 */
}

.article-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 15px;
  line-height: 1.3;
}

.article-meta {
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 14px;
}

.article-content {
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 使内容居中 */
}

.article-image {
  width: 85%; /* 控制图片宽度 */
  height: auto;
  margin: 0 auto 20px; /* 居中显示 */
  border-radius: 4px;
  display: block; /* 确保图片居中 */
}

.article-text {
  font-size: 18px;
  line-height: 1.8;
  color: #333;
  width: 100%; /* 确保文字占满宽度 */
  text-indent: 2em;
}

.clickable-word {
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-block;
  padding: 0 2px;
  user-select: none; /* 防止文本被选中 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.clickable-word:hover {
  color: #1890ff;
  background-color: rgba(24, 144, 255, 0.1);
  border-radius: 2px;
}

[theme-mode="dark"] .clickable-word:hover {
  color: #177ddc;
  background-color: rgba(23, 125, 220, 0.1);
}

[theme-mode="dark"] .page-wrapper {
  background-color: #242424;
}

[theme-mode="dark"] .article-container {
  background: transparent;
}

[theme-mode="dark"] .article-title {
  color: #fff;
}

[theme-mode="dark"] .article-meta {
  color: #999;
}

[theme-mode="dark"] .article-text {
  color: #ccc;
}

[theme-mode="dark"] .article-header {
  border-color: #333;
}

.anchor-nav {
  position: fixed;
  left: 40%;
  margin-left: -500px;
  top: 50%;
  transform: translateY(-50%);
  width: 150px;
  max-height: 80vh;
  overflow-y: auto;
  background: #fff;
  border-right: 1px solid #e2e2e2;
  padding: 15px;
}

.anchor-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  padding-left: 10px;
  color: #fff;
}

.content-section-title {
  width: 100%;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 20px 0;
  text-indent: 2em;
}

.anchor-list {
  display: flex;
  flex-direction: column;
}

.anchor-item {
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.3s;
}

.anchor-item:hover {
  background: #f5f5f5;
}

.anchor-item.active {
  background: #e6f7ff;
  color: #1890ff;
}

[theme-mode="dark"] .anchor-nav {
  background: #242424;
  border-color: #333;
}

[theme-mode="dark"] .anchor-item {
  color: #fff;
}

[theme-mode="dark"] .anchor-item:hover {
  background: #333;
}

[theme-mode="dark"] .anchor-item.active {
  background: #333;
  color: #fff;
}

[theme-mode="dark"] .anchor-title {
  color: #fff;
}

[theme-mode="dark"] .content-section-title {
  color: #fff;
}

.right-sidebar {
  position: relative;
  z-index: 100;
}

/* 暗黑模式适配 */
[theme-mode="dark"] .right-sidebar :deep(.t-sticky-tool) {
  background-color: #242424 !important;
}

[theme-mode="dark"] .right-sidebar :deep(.t-sticky-item) {
  color: #fff;
}

.anchor-section {
  margin-bottom: 16px;
}

.anchor-section-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  padding: 6px 10px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.anchor-section-title:hover {
  background: #f5f5f5;
}

.anchor-section-items {
  margin-left: 12px;
  margin-top: 8px;
}

[theme-mode="dark"] .anchor-section-title {
  color: #fff;
}

[theme-mode="dark"] .anchor-section-title:hover {
  background: #333;
}

.section-anchor {
  position: absolute;
  visibility: hidden;
  height: 0;
  width: 0;
  margin: 0;
  padding: 0;
  border: none;
}

.reading-quiz {
  width: 100%;
  padding: 20px;
  margin-top: 30px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.quiz-question h3 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

.quiz-question p {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 20px;
  color: #444;
}

.quiz-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quiz-option {
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 12px;
}

.quiz-option:hover {
  background-color: #f0f0f0;
}

.option-label {
  font-weight: 600;
  color: #666;
  min-width: 24px;
}

.quiz-option.selected {
  border-color: #1890ff;
}

.quiz-option.correct {
  background-color: #f6ffed;
  border-color: #52c41a;
}

.quiz-option.incorrect {
  background-color: #fff2f0;
  border-color: #ff4d4f;
}

.quiz-result {
  margin-top: 20px;
  padding: 16px;
  border-radius: 6px;
}

.result-correct {
  color: #52c41a;
  font-weight: 600;
}

.result-incorrect {
  color: #ff4d4f;
}

.result-incorrect span {
  font-weight: 600;
}

.explanation {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

[theme-mode="dark"] .reading-quiz {
  background-color: #1a1a1a;
}

[theme-mode="dark"] .quiz-question h3,
[theme-mode="dark"] .quiz-question p {
  color: #fff;
}

[theme-mode="dark"] .quiz-option {
  border-color: #333;
  color: #fff;
}

[theme-mode="dark"] .quiz-option:hover {
  background-color: #2a2a2a;
}

[theme-mode="dark"] .option-label {
  color: #999;
}

[theme-mode="dark"] .explanation {
  color: #999;
}

.anchor-section-title.active {
  color: #1890ff;
  background-color: #e6f7ff;
}

[theme-mode="dark"] .anchor-section-title.active {
  background-color: #111b26;
}

/* 词汇本和翻译本面板样式 */
.side-panel {
  position: fixed;
  top: 0;
  right: -320px;
  width: 320px;
  height: 100vh;
  background-color: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  transition: right 0.3s ease;
  z-index: 1000;
}

.side-panel.show {
  right: 0;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e2e2e2;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #666;
  cursor: pointer;
  padding: 0 8px;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #333;
}

.panel-content {
  height: calc(100vh - 60px);
  overflow-y: auto;
  padding: 0;
}

.vocabulary-item,
.grammar-item {
  padding: 12px;
  margin-bottom: 12px;
  border-radius: 6px;
  background-color: #f8f9fa;
  transition: all 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.vocabulary-item:hover,
.grammar-item:hover {
  background-color: #e9ecef;
}

.item-content {
  flex: 1;
}

.delete-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: none;
  background-color: #ff4d4f;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  opacity: 0;
  transition: all 0.3s;
}

.vocabulary-item:hover .delete-btn,
.grammar-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  background-color: #ff7875;
}

[theme-mode="dark"] .delete-btn {
  background-color: #a61d24;
}

[theme-mode="dark"] .delete-btn:hover {
  background-color: #cf1322;
}

/* 暗黑模式样式 */
[theme-mode="dark"] .side-panel {
  background-color: #242424;
}

[theme-mode="dark"] .panel-header {
  border-color: #333;
}

[theme-mode="dark"] .panel-header h3 {
  color: #fff;
}

[theme-mode="dark"] .close-btn {
  color: #999;
}

[theme-mode="dark"] .close-btn:hover {
  color: #fff;
}

[theme-mode="dark"] .vocabulary-item,
[theme-mode="dark"] .grammar-item {
  background-color: #2a2a2a;
}

[theme-mode="dark"] .vocabulary-item:hover,
[theme-mode="dark"] .grammar-item:hover {
  background-color: #333;
}

/* 自定义滚动条样式 */
.panel-content::-webkit-scrollbar {
  width: 6px;
}

.panel-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.panel-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.panel-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

[theme-mode="dark"] .panel-content::-webkit-scrollbar-track {
  background: #333;
}

[theme-mode="dark"] .panel-content::-webkit-scrollbar-thumb {
  background: #666;
}

[theme-mode="dark"] .panel-content::-webkit-scrollbar-thumb:hover {
  background: #888;
}

.translate-button {
  position: absolute;
  width: 32px;
  height: 32px;
  z-index: 1000;
  cursor: pointer;
}

.translate-icon {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: background-color 0.3s;
}

.translate-icon:hover {
  background-color: #40a9ff;
}

.close-translate-button {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 16px;
  height: 16px;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #666;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.close-translate-button:hover {
  background-color: #f5f5f5;
  color: #333;
}

[theme-mode="dark"] .translate-icon {
  background-color: #177ddc;
}

[theme-mode="dark"] .translate-icon:hover {
  background-color: #3c9ae8;
}

[theme-mode="dark"] .close-translate-button {
  background-color: #333;
  color: #999;
}

[theme-mode="dark"] .close-translate-button:hover {
  background-color: #444;
  color: #fff;
}

.translate-panel {
  position: absolute;
  background-color: white;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 200px;
  max-width: 300px;
}

.panel-arrow {
  position: absolute;
  top: 10px;
  left: -8px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid white;
}

.translate-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

[theme-mode="dark"] .translate-panel {
  background-color: #1f1f1f;
  border: 1px solid #333;
}

[theme-mode="dark"] .panel-arrow {
  border-right-color: #1f1f1f;
}

[theme-mode="dark"] .translate-content {
  color: #fff;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 10px auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

[theme-mode="dark"] .loading-spinner {
  border: 2px solid #333;
  border-top: 2px solid #177ddc;
}

.translate-content {
  min-height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.discussion-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-messages {
  flex: 0.9;
  overflow-y: auto;
  padding: 20px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.message-left {
  flex-direction: row;
}

.message-right {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  max-width: 70%;
}

.message-info {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.message-name {
  font-weight: 500;
  margin-right: 8px;
}

.message-time {
  color: #999;
}

.message-text {
  padding: 12px;
  background-color: #f0f2f5;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

.message-right .message-text {
  background-color: #e6f4ff;
}

.message-actions {
  display: flex;
  gap: 8px;
  margin-top: 4px;
  justify-content: flex-start;
}

.action-btn {
  background: none;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.action-btn:hover {
  background-color: #f0f2f5;
}

.action-btn.active {
  background-color: #e6f4ff;
  color: #1890ff;
}

.chat-input {
  padding: 12px 16px;
  border-top: 1px solid #e8e8e8;
  background-color: #fff;
  position: sticky;
  bottom: 0;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 12px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  padding: 8px 12px;
}

.input-container textarea {
  flex: 1;
  border: none;
  padding: 0;
  resize: none;
  font-size: 14px;
  line-height: 1.5;
  background: transparent;
  height: 24px;
  max-height: 24px;
  overflow-y: hidden;
}

.input-container textarea:focus {
  outline: none;
}

.send-btn {
  padding: 0 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  height: 32px;
  min-width: 60px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover {
  background-color: #40a9ff;
}

.send-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 暗黑模式适配 */
[theme-mode="dark"] .message-text {
  background-color: #2a2a2a;
  color: #fff;
}

[theme-mode="dark"] .message-right .message-text {
  background-color: #111b26;
}

[theme-mode="dark"] .chat-input {
  background-color: #242424;
  border-top-color: #333;
}

[theme-mode="dark"] .input-container textarea {
  background-color: #2a2a2a;
  border-color: #333;
  color: #fff;
}

[theme-mode="dark"] .input-container textarea:focus {
  border-color: #177ddc;
}

[theme-mode="dark"] .action-btn:hover {
  background-color: #2a2a2a;
}

[theme-mode="dark"] .action-btn.active {
  background-color: #111b26;
  color: #177ddc;
}

[theme-mode="dark"] .message-info {
  color: #999;
}

[theme-mode="dark"] .message-time {
  color: #666;
}

/* 添加聊天loading样式 */
.message-loading {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.chat-loading {
  width: 24px;
  height: 8px;
  border-radius: 4px;
  display: inline-flex;
}

.chat-loading-moving {
  background: linear-gradient(90deg, #e0e0e0 25%, #f5f5f5 50%, #e0e0e0 75%);
  background-size: 200% 100%;
  animation: loading-moving 1.5s infinite;
}

.chat-loading-gradient {
  background: linear-gradient(90deg, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3));
  animation: loading-gradient 1.5s infinite alternate;
}

@keyframes loading-moving {
  0% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes loading-gradient {
  from {
    opacity: 0.3;
  }
  to {
    opacity: 0.8;
  }
}

[theme-mode="dark"] .chat-loading-moving {
  background: linear-gradient(90deg, #333 25%, #444 50%, #333 75%);
  background-size: 200% 100%;
}

[theme-mode="dark"] .chat-loading-gradient {
  background: linear-gradient(90deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.3));
}

.word-detail-panel {
  position: fixed;
  top: 0;
  right: -400px;
  width: 400px;
  height: 100vh;
  background-color: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  transition: right 0.3s ease;
  z-index: 1000;
}

.word-detail-panel.show {
  right: 0;
}

.word-section {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.section-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.section-content {
  font-size: 16px;
  color: #333;
  line-height: 1.6;
}

.example-sentences {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.example-item {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
}

.example-item .english {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.example-item .chinese {
  font-size: 14px;
  color: #666;
}

[theme-mode="dark"] .word-detail-panel {
  background-color: #242424;
}

[theme-mode="dark"] .word-section {
  border-color: #333;
}

[theme-mode="dark"] .section-title {
  color: #999;
}

[theme-mode="dark"] .section-content {
  color: #fff;
}

[theme-mode="dark"] .example-item {
  background-color: #2a2a2a;
}

[theme-mode="dark"] .example-item .english {
  color: #fff;
}

[theme-mode="dark"] .example-item .chinese {
  color: #999;
}
</style>